////////////////////////////////////////////////////////////////////
// File:	Mesh.cpp
// Purpose: Defines the components of a mesh and a skinned mesh
//			seperately so the MeshManager can retrieve/access data and
//			manipulate it relatively easily.
// Author:	Jay Baird
////////////////////////////////////////////////////////////////////

#include "Mesh.h"
#include <windows.h>
#include <glee.h>
#include <gl.h>

using namespace MeshComponent;

SkinnedMesh::SkinnedMesh(const Mesh& m)
{
	operator=(m);
}

SkinnedMesh& SkinnedMesh::operator=(const Mesh& m)
{
	if(this == &m) return *this;

	this->m_triangles = (Triangle*)m.GetTriangles();
	this->m_vertices = (vec3*)m.GetVertices();
	this->m_normals = (vec3*)m.GetNormals();
	this->m_texCoords = (vec2*)m.GetTexCoords();
	this->m_numTriangles = m.GetTriangleCount();
	this->m_numVertices = m.GetVertexCount();
	this->m_texTiles = m.GetTextureTileCount();

	return *this;
}

void Mesh::Delete()
{
	if(m_triangles) delete[] m_triangles;
	if(m_texCoords) delete[] m_texCoords;
	if(m_vertices) delete[] m_vertices;
	if(m_normals) delete[] m_normals;

	m_triangles = NULL;
	m_texCoords = NULL;
	m_texCoords = NULL;
	m_vertices = NULL;
	m_normals = NULL;

	// Delete the VBOs
	if(m_buffer.buffers[MESH_BUFFER_TYPE_VERTEX] != 0)
	{
		if(Type() == MESH_TYPE_SKINNED_MESH)
		{
			glBindBuffer(GL_ARRAY_BUFFER, m_buffer.buffers[MESH_BUFFER_TYPE_VERTEX]);
			glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_DYNAMIC_DRAW);
		}

		glDeleteBuffers(1, &m_buffer.buffers[MESH_BUFFER_TYPE_VERTEX]);
	}
	if(m_buffer.buffers[MESH_BUFFER_TYPE_NORMAL] != 0)
		glDeleteBuffers(1, &m_buffer.buffers[MESH_BUFFER_TYPE_NORMAL]);
	if(m_buffer.buffers[MESH_BUFFER_TYPE_TEXCOORD] != 0)
		glDeleteBuffers(1, &m_buffer.buffers[MESH_BUFFER_TYPE_TEXCOORD]);
	if(m_buffer.buffers[MESH_BUFFER_TYPE_INDEX] != 0)
		glDeleteBuffers(1, &m_buffer.buffers[MESH_BUFFER_TYPE_INDEX]);

	// Reset all buffers to zero
	memset(m_buffer.buffers, 0, sizeof(unsigned) * MESH_BUFFER_TYPE_MAX);

	// Unbind buffers
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}